import Util from '@/utils/index'
// import {router} from '@/router/index'
// 配置API接口地址
var rootList = [
	// 'http://liudashi.f3322.net:9001'
	// 'http://111.206.102.29:9001'
	// 'http://192.160.27.26:9001'
	'http://103.36.192.87:9001'
]
sessionStorage.uploadUrl = rootList[0]
// 引用axios
var axios = require('axios')
var qs = require('qs')
// 自定义判断元素类型JS
function toType (obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 参数过滤函数
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
/*
  接口处理函数
*/

function apiAxios (root, method, url, params, callback) {
	var token = ''
  if (params) {
    params = filterNull(params)
  }
	if (url === '/auth/user/login') {
		token = ''
	} else {
		let tokenDate = Number(sessionStorage.tokenDate)
		let date = new Date()
		if (date.getTime() > (tokenDate + 1000 * 60 * 10)) {
			sessionStorage.removeItem('user')
			sessionStorage.removeItem('tokenDate')
			sessionStorage.removeItem('aselect')
			sessionStorage.removeItem('anavList')
			sessionStorage.removeItem('aselected')
			sessionStorage.removeItem('aname')
			// router.push({
			// 	name: 'login'
			// })
			location.href = '/login.html'
		} else {
			sessionStorage.tokenDate = date.getTime()
		}
    token = Util.getToken()
		// console.log(token)
	}
  var paramsStr = qs.stringify(params)
	if (method === 'GET' || method === 'DELETE') {
		if (url.indexOf('?') === -1) {
			if (JSON.stringify(params) !== '{}') {
				let pArry = []
				for (let key in params) {
					pArry.push({'key': key, 'value': params[key]})
				}
				for (let i = 0; i < pArry.length; i++) {
					if (i === 0) {
						url += '?' + pArry[i].key + '=' + pArry[i].value
					} else {
						url += '&' + pArry[i].key + '=' + pArry[i].value
					}
				}
			}
		}
	}
  axios({
    method: method,
    url: url,
    data: ['POST', 'PUT'].indexOf(method) !== -1 ? paramsStr : null,
    // params: (method === 'GET' || method === 'DELETE') ? null : paramsStr,
    baseURL: rootList[root],
    withCredentials: false,
    headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'Authorization': token,
			'Access-Control-Allow-Origin': '*'
    },
		credentials: true
  })
  .then(function (res) {
    callback(res)
  })
  .catch(function (err) {
    if (err) {
      console.log('载入错误，' + err)
    }
  })
}

// 返回在vue模板中的调用接口
export default {
  get: function (root, url, params, callback) {
    return apiAxios(root, 'GET', url, params, callback)
  },
  post: function (root, url, params, callback) {
    return apiAxios(root, 'POST', url, params, callback)
  },
	put: function (root, url, params, callback) {
		return apiAxios(root, 'PUT', url, params, callback)
	},
	delete: function (root, url, params, callback) {
		return apiAxios(root, 'DELETE', url, params, callback)
	}
}
